/*
 *  Copyright (C) 2013 KangHua <kanghua151@gmail.com> 
 *
 *  This program is free software; you can redistribute it and/or modify it
 *  under the terms of the GNU General Public License version 2 as published by
 *  the Free Software Foundation.
 */

#include <stdio.h>
#include <time.h>
#include <sys/time.h>
#include <stdint.h>
#include <fcntl.h>
#include <signal.h>
#include "glib.h"
#include "ffssim_ctrl.h"
#include "storage.h"
#include "bs_local.h"

#define HLOG_DEBUG		printf
#define HLOG_ERROR		printf

struct back_storage *init_storage_handler(const char *uri)
{
	HLOG_DEBUG("enter func %s", __func__);
	int ret = 0;
	struct back_storage *storage = NULL;
	gchar *back_storage_type = NULL;
	char *head = NULL;
	char *hostname = NULL;
	char *dir = NULL;
	char *fs_name = "FFSSIM";
	int port;
#if 0
	ret = parse_from_uri(uri, &head, &hostname, &dir, &fs_name, &port);
	if (ret != 0) {
		HLOG_ERROR("parse_from_uri happened error");
		return NULL;
	}
#endif
	HLOG_DEBUG("loc [fs:%s], \n",fs_name);
	storage = get_local_storage_ops();
	storage->uri = g_strdup(uri);
	storage->head = head;
	storage->dir = g_strdup(uri);
	storage->fs_name = fs_name;
	storage->hostname = hostname;
	storage->port = port;
	storage->user = g_strdup("kanghua");
	HLOG_DEBUG("uri:%s, head:%s, dir:%s, fsname:%s, hostname:%s,port:%d, user:%s",
			storage->uri,
			storage->head,
			storage->dir,
			storage->fs_name,
			storage->hostname,
			storage->port,
			storage->user);
#if 0
	if (0 != storage->bs_fs_connect(storage, uri)) {
		ret = -1;
		HLOG_ERROR("connect filesystem failed");
		goto out;
		return NULL;
	}
out:
	if (ret != 0) {
		g_free(storage);
		HLOG_ERROR("ret is not 0, so error happened");
		storage = NULL;
	}
#endif
	HLOG_DEBUG("leave func %s", __func__);
	return storage;
}

int read_fs_sb_meta(struct back_storage *storage,uint32_t *block_size,uint64_t *max_fs_size,uint32_t *chunk_size)
{
	gchar *sb_filename=g_build_filename(storage->dir,storage->fs_name, \
			"superblock",NULL);
	GKeyFile *sb_keyfile=g_key_file_new();
	GError *sb_error= g_error_new(G_FILE_ERROR,G_FILE_ERROR_NOENT,\
			"File execute wrong!");
	if(!g_key_file_load_from_file(sb_keyfile,(const)sb_filename,\
				G_KEY_FILE_NONE,&sb_error))
	{
		HLOG_ERROR("SuperBlock load from file fail:%s\n",sb_error->message);
		exit(EXIT_FAILURE);
	}

	*block_size=g_key_file_get_integer (sb_keyfile,"METADATA","block_size",NULL);
 	*max_fs_size=g_key_file_get_int64 (sb_keyfile,"METADATA","max_fs_size",NULL);
	*chunk_size=g_key_file_get_integer (sb_keyfile,"METADATA","chunk_size",NULL);
	if(0==(*block_size)||0==(*max_fs_size)||0==(*chunk_size))
	{
		HLOG_ERROR("Metadata get fail!");
		exit(EXIT_FAILURE);
	}
 	return 0;
}
